window.onload = function() {
    init();
}

function init() {
    initMagnifier();
}
var initMagnifier = (function() {
    var oImgWrap = document.getElementsByClassName('img-wrap')[0],
        oMageWrap = oImgWrap.getElementsByClassName('mag-wrap')[0],
        oMagImg = oMageWrap.getElementsByClassName("mag-img")[0],
        magWidth = getStyle(oMageWrap, 'width'),
        magHeight = getStyle(oMageWrap, 'height'),
        imgX = oImgWrap.offsetLeft,
        imgY = oImgWrap.offsetTop;
    addEvent(oImgWrap, 'mouseover', function(e) {
        var e = e || window.event,
            x = pagePos(e).x - imgX - magWidth / 2,
            y = pagePos(e).y - imgY - magHeight / 2;
        showMag(x, y);
        oMageWrap.className += ' show'
        addEvent(document, 'mousemove', mouseMove);
    })
    addEvent(oImgWrap, 'mouseout', mouseOut)

    function mouseMove(e) {
        var e = e || window.event,
            x = pagePos(e).x - imgX - magWidth / 2,
            y = pagePos(e).y - imgY - magHeight / 2,
            mouseX = pagePos(e).x - imgX,
            mouseY = pagePos(e).y - imgY;
        showMag(x, y, mouseX, mouseY);
        oMageWrap.className += ' show'

    }

    function mouseOut() {
        oMageWrap.className = 'mag-wrap'
        removeEvent(document, 'mousemove', mouseMove);
    }

    function showMag(x, y, mouseX, mouseY) {
        oMageWrap.style.left = x + 'px';
        oMageWrap.style.top = y + 'px';
        console.log(-x + 'px');
        oMagImg.style.left = -x + 'px';
        oMagImg.style.top = -y + 'px';
        if (mouseX && mouseY) {
            if (mouseX < 0 || mouseX > getStyle(oImgWrap, 'width') ||
                mouseY < 0 || mouseY > getStyle(oImgWrap, 'height')) {
                oMageWrap.className = 'mag-wrap'
            }
        }
    }
});